using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;

namespace DotConferenceSql
{
    /// <summary>
    /// QueryElement that list every WHERE statement
    /// separated by AND or OR
    /// </summary>
    public class WhereClauseQueryElement : CompositeQueryElement
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WhereClauseQueryElement"/> class.
        /// </summary>
        public WhereClauseQueryElement()
            : base()
        {
            Type = QueryElementType.WhereClause;
        }

        /// <summary>
        /// Aggregate the parameters from the elements
        /// and generate the complete list of parameters
        /// for BuildSqlCommand()
        /// </summary>
        /// <returns></returns>
        public override List<SqlParameter> ListParameters()
        {
            return base.ListParameters();
        }

        /// <summary>
        /// Generate a SQL query
        /// </summary>
        /// <returns>generated SQL query</returns>
        public override string BuildTextQuery()
        {
            StringBuilder finalStatement = new StringBuilder();
            int count = 0;
            foreach (QueryElementBase element in Elements)
            {
                finalStatement.Append(element.BuildTextQuery());
                if (++count < Elements.Count)
                {
                    if (element is WhereStatementQueryElementBase)
                    {
                        WhereStatementQueryElementBase whereStatement = element as WhereStatementQueryElementBase;
                        finalStatement.Append(whereStatement.ExclusiveCheck ? " AND " : " OR ");
                    }
                    else
                    {
                        finalStatement.Append(" AND ");
                    }
                }
            }

            return finalStatement.ToString();
        }
    }
}